package com.shop.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.shop.bean.*;
import com.shop.dao.CartDao;
import com.shop.dao.OrdersDao;
import com.shop.dao.ProductDao;
import com.shop.dao.UserAddressDao;
import com.shop.service.IOrdersService;
import com.shop.util.Page;
import com.shop.util.PaymentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Service
public class OrdersService implements IOrdersService {
    @Autowired
    ProductDao productDao;
    @Autowired
    OrdersDao orderDao;
    @Autowired
    UserAddressDao userAddressDao;
    @Autowired
    CartDao cartDao;
    @Transactional//确保事务
    @Override
    public int addOrder(List<Integer> ids, List<Integer> quantities, Integer addressid, Integer userid) {
        //参数检查
        // 1 两个集合中的数据数量要一样
        // 2.numbers中的数字不能下于1
        int idssize=-1;
        int numsize=-1;
        if(ids!=null&&quantities!=null){
            idssize=ids.size();
            numsize=quantities.size();
            if(!(idssize>0&&numsize>0&&idssize==numsize)){
                throw new RuntimeException("参数异常");
            }
        }else{
            throw new RuntimeException("参数异常");
        }
        //获取商品数据
        List<Order_details> orderInfoList=new ArrayList<>();
        BigDecimal total=new BigDecimal("0");
        int id=0;
        int quantity=0;
        for(int i=0;i<ids.size();i++){
            id=ids.get(i);//商品的id值
            quantity=quantities.get(i);//需要购买的数量
            Product pro=productDao.getProductById(id);
            if(pro==null){
                throw new RuntimeException("商品参数异常");
            }
            Order_details info=new Order_details();
            String mainImageUrl = "";
            if (pro.getImgurl().size() > 0) {
                for (int j = 0; j < pro.getImgurl().size(); j++) {
                    if (pro.getImgurl().get(j).getIs_main() == 1) {
                        mainImageUrl = pro.getImgurl().get(j).getImgurl();
                        break;
                    }
                }
            }
            info.setImgurl(mainImageUrl);
            info.setQuantity(quantity);
            info.setPrice(pro.getPrice());
            info.setName(pro.getName());
            info.setProductid(pro.getId());
            orderInfoList.add(info);
            //计算总价格
            total=total.add(pro.getPrice().multiply(new BigDecimal(quantity)));
        }

        //封装订单
        Orders order=new Orders();
        //在前面拼接上一个新的名字，尽量不重复   雪花算法
        String uuid= UUID.randomUUID().toString();
        order.setCode(uuid);
        order.setMoney(total);
        order.setUserid(userid);
        //保存   获取订单id(自增长)
        orderDao.addOrder(order);
        int orderid=order.getId();//获取自增长主键
        for(Order_details info:orderInfoList){
            info.setOrderid(orderid);
        }
        //封装订单明细
        orderDao.addOrderInfo(orderInfoList);
        //获取地址
        Address userAddress=userAddressDao.getAddressByID(addressid);
        if(userAddress==null){
            throw new RuntimeException("收货地址参数异常");
        }
        StringBuilder strB=new StringBuilder();
        strB.append(userAddress.getProvince());
        strB.append("-");
        strB.append(userAddress.getCity());
        strB.append("-");
        strB.append(userAddress.getArea());
        strB.append("-");
        strB.append(userAddress.getAddress());
        String address= strB.toString();
        //处理地址
        Order_address orderAddress=new Order_address();
        orderAddress.setOrderid(orderid);
        orderAddress.setAddress(address);
        orderAddress.setName(userAddress.getName());
        orderAddress.setPhone(userAddress.getPhone());
        //封装地址
        orderDao.addOrderAddress(orderAddress);
        //删除购物车中的数据
        for(Integer item:ids){
            Cart cart=new Cart();
            cart.setUser_id(userid);
            cart.setProduct_id(item);
            cartDao.delete(cart);
        }
        return orderid;
    }

    @Override
    public String payment(Integer id) {
        Orders order=orderDao.getOrderByID(id);
        if(order==null){
            throw new RuntimeException("订单不存在") ;
        }
        if(order.getState()==-1){
            throw new RuntimeException("订单已失效") ;
        }
        if(order.getState()!=0){
            throw new RuntimeException("订单已支付") ;
        }
        //准备支付--生成二维码
        String url=null;
        try {
            url= PaymentUtil.payment(order);
            System.out.println(url+"-----------------");
        }catch(Exception e){
            throw new RuntimeException("支付服务异常") ;
        }
        //生成二维码图片
        BufferedImage img=QrCodeUtil.generate(url, 300, 300);
        //将图片传成Base64编码
        String qrcode=ImgUtil.toBase64(img,"png");
        System.out.println(qrcode+"-------------------211");
        return qrcode;
    }

    public int paymentSuccess(HashMap map){
        //检查订单是否存在,是否是阿里后台的回调
        String code=(String)map.get("out_trade_no");
        return  orderDao.paymentSuccess(code);
    }

    public Orders getOrderByID(Integer id){
        return orderDao.getOrderByID(id);
    }


    public int cancleOrder(){
        return orderDao.cancleOrder();
    }

    public List<Orders> getOrderByUserID(Integer userid){
        return orderDao.getOrderByUserID(userid);
    };


    @Override
    public int getCount(String text) {
        return orderDao.getCount(text);
    }


    @Override
    public List<Orders> selectOrders(Page page, String text) {
        return orderDao.selectOrders(page, text);
    }

    @Override
    public int deleteOrder(int id) {
        return orderDao.deleteOrder(id);
    }

    @Override
    public Order_address getAddress(int orderid) {
        return orderDao.getAddress(orderid);
    }

    @Override
    public int putOn(int orderid) {
        return orderDao.putOn(orderid);
    }

    @Override
    public int get(int orderid) {
        return orderDao.get(orderid);
    }

    @Override
    public int end(int orderid) {
        return orderDao.end(orderid);
    }

    @Override
    public String getDescription(Integer orderid) {
        List<Order_details> orderDetails = orderDao.getDetails(orderid);

        StringBuilder description = new StringBuilder();

        for (Order_details orderDetail : orderDetails) {
            description.append("商品ID: ").append(orderDetail.getProductid())
                    .append("\n商品名称: ").append(orderDetail.getName())
                    .append("\n商品数量: ").append(orderDetail.getQuantity())
                    .append("\n商品单价: ").append(orderDetail.getPrice())
                    .append("\n");
        }

        return description.toString();
    }
}
